/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3-详情  4-交收
    info：type=3||4时，需回填字段
    onRef：组件指针
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    reset：通过onRef，调用reset方法，清空页面字段
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { PrimaryC, ModalC, PrimaryGhostC, TableC } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Modal } from 'antd';
import style from './index.less';
import { connect } from 'dva';
import OrderFormC from './orderFormC';
import { uniqueKey, AutomaticSettlement } from '../../../../utils/commonFunc';

class AddOrderC extends PureComponent {
  static defaultProps = {
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //详情
    type: undefined, //当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    isShow: false, //二次确认模态框显示隐藏
    querys: {}, //二次确认详情数据
    isCanOrder: true, //组合是否可以下达 默认可以
    trailColumns: [], //试算结果列表
    trailDataSource: [], //试算结果数据
    trailModel: false, //试算模态框
    productCode: undefined, //产品code
    portfolioCode: undefined, //组合code
    uid: '',
  };
  componentDidMount() {
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }
  //用户点击下达或确定按钮
  onOk = () => {
    const { type, money, position } = this.props;
    if (!this.state.isCanOrder && type == 1) {
      message.warning(this.props.errorSetMsg);
      return;
    }
    const data = this.orderForm.getInfo();
    //校验页面数据
    if (!data) return;
    data.uid = this.state.uid;
    if (data.priceqj < data.price) {
      message.error('净价价格不能大于全价价格!');
      return;
    }
    if (type != 10) {
      //交易录入不进行校验
      if (data.direction == 1) {
        if (parseFloat(money.t0 || 0) < parseFloat(data.parValueTotalqj)) {
          message.error('全价总额不能大于t+0可用!');
          return;
        }
      }
      if (data.direction == 2) {
        if (parseFloat(position.available || 0) - parseFloat(data.amount) < 0) {
          message.error('数量不能大于可用数量!');
          return;
        }
      }
    }
    if (type == 1) {
      if (this.state.isShow) {
        this.confirmOk(data); //二次确认的确定 点击按钮
      } else {
        //指令下达需要二次确认
        this.setState({
          querys: data,
          isShow: true,
        });
      }
    } else {
      //簿记无需二次确认 直接请求后端
      this.confirmOk(data);
    }
  };
  //用户点击取消
  onCancel = () => {
    this.orderForm.reset();
    this.setState({
      isCanOrder: true,
    });
    this.props.onCancel();
  };
  confirmOk = (params) => {
    //指令下达 簿记保存请求后台
    const { dispatch, type } = this.props;
    let url = '';
    switch (type) {
      // 指令
      case 1 || '1':
        url = 'finaFlockingM/orderSave';
        break;
      // 簿记
      case 2 || '2':
        url = 'finaFlockingM/tradeBookSave';
        break;
      // 存续管理
      case 10 || '10':
        url = 'finaFlockingM/tradeAdd';
        break;
      //组合试算
      case 11 || '11':
        url = 'portfolioTrialAddM/finaFlockingSave';
        break;
      // 多基金
      case 12 || '12':
        url = 'moreFundsOrderM/finaFlockingAdd';
        break;
    }
    if (type == 2 || type == 10 || type == 11 || type == 12) {
      //簿记下达 多基金指令
      params.method = '0';
      params.tradeInstruction = { direction: params.direction, stockCode: params.tradingcode };
    }
    if (type == 10) {
      //交易录入 需要
      params.productid = params.portfolioid;
    }
    if (type == 2) {
      // 判断租户是否配置自动交收，若配置自动交收给予弹窗提醒
      if (
        AutomaticSettlement(type, url, params, dispatch, (res) => {
          if (res && res.success) {
            //簿记下达成功
            this.props.onOk();
            this.onCancel(); //初始化form表单
            message.success('簿记下达成功!');
          } else {
            message.error(res ? res.message : '簿记下达失败!');
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        })
      )
        return;
    }
    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (res) => {
        if (res && res.success) {
          if (type == 2 || type == 10 || type == 11 || type == 12) {
            //簿记下达成功 交易录入成功
            this.props.onOk();
            this.onCancel(); //初始化form表单
          } else {
            //指令下达成功
            this.onCancel(); //初始化form表单
            this.handleCancel(); //关闭模态框
          }
          if (type == 12) {
            return;
          }
          message.success(type == 1 ? '指令下达成功!' : type == 2 ? '簿记下达成功!' : type == 11 ? '组合试算下达成功' : '交易录入成功!');
        } else {
          if (type == 12) {
            return;
          }
          message.error(res ? res.message : type == 1 ? '指令下达失败!' : type == 2 ? '簿记下达失败!' : type == 11 ? '组合试算下达失败' : '交易录入失败!');
        }
        const uid = uniqueKey();
        uid.then((r) => {
          this.setState({ uid: r });
        });
      },
    });
  };
  //二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };
  // 二次确认modal框
  showModal = () => {
    const { querys, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 700,
      height: 1000,
      className: 'confirmOrder',
      confirmLoading: loading.effects['finaFlockingM/orderSave'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.onOk} onCancel={this.handleCancel}>
        <OrderFormC type={'3'} info={querys} />
      </ModalC>
    );
  };
  queryIsAccountConfigured = (value) => {
    if (value) {
      this.props.dispatch({
        //校验组合下是否有组合配置
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: value,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else {
      this.setState({
        isCanOrder: true,
      });
    }
  };
  //试算按钮点击
  trialOnClick = () => {
    const {
      dispatch,
      user: { currentUser },
    } = this.props;
    const data = this.orderForm.getInfo();

    //校验页面数据
    if (!data) return;
    if (data.priceqj < data.price) {
      message.error('净价价格不能大于全价价格!');
      return;
    }
    data.method = '0';
    data.tradeInstruction = { direction: data.direction, stockCode: data.tradingcode };

    let querys = {
      productCode: this.state.productCode, //产品code
      portfolioCode: this.state.portfolioCode, //组合code
      tenant: currentUser.tenant, //租户code
      businessType: '6',
      type: '6',
      trade6: data,
    };
    this.setState({ trailModel: true }, () => {
      dispatch({
        type: 'trailM/trialData',
        payload: querys,
        callback: (res) => {
          if (res) {
            this.setState({
              trailColumns: res.columns,
              trailDataSource: res.dataSource,
            });
          } else {
            this.setState({
              trailColumns: [],
              trailDataSource: [],
            });
          }
        },
      });
    });
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };
  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };
  render() {
    const { loading, type } = this.props;
    return (
      <div>
        <div className={'backBg'}>
          <OrderFormC
            type={this.props.type}
            portfolioOnChange={(e) => {
              this.props.portfolioOnChange(e);
              if (this.props.type == '1') this.queryIsAccountConfigured(e); //指令下达的时候进行校验组合是否配置
            }}
            tradingcodeOnChange={this.props.tradingcodeOnChange}
            productGroupOnChange={this.props.productGroupOnChange}
            listId={this.props.listId}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            investmentType={this.props.type > 3 && this.props.type != 12 ? undefined : this.props.position.investmentType}
            onRef={(ref) => {
              this.orderForm = ref;
            }}
          />
        </div>
        <div style={{ marginTop: '20px' }} className={style.btnOperate}>
          {/* {type == "2" && <PrimaryC
                        loading={loading.effects['trailM/trialData'] === true}
                        onClick={() => this.trialOnClick()}
                        title={'试算'}
                        style={{ marginRight: "10px" }}
                    />} */}
          <PrimaryC
            loading={
              loading.effects['finaFlockingM/tradeBookSave'] === true ||
              loading.effects['finaFlockingM/tradeAdd'] === true ||
              loading.effects['portfolioTrialAddM/finaFlockingSave'] === true ||
              loading.effects['moreFundsOrderM/finaFlockingAdd'] === true
            }
            onClick={this.onOk}
            title={this.props.type == 1 ? '下达' : '确定'}
          />
          <PrimaryGhostC onClick={this.onCancel} title='取消' style={{ marginLeft: '10px' }} />
        </div>
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
        {this.state.trailModel && this.showTrail()}
      </div>
    );
  }
}
export default connect(({ finaFlockingM, userM: user, portfolioTrialAddM, loading, isAccountConfiguredM, moreFundsOrderM }) => ({
  finaFlockingM,
  user,
  portfolioTrialAddM,
  loading,
  errorSetMsg: isAccountConfiguredM.msg,
  isAccountConfiguredM,
  moreFundsOrderM,
}))(Form.create()(AddOrderC));
